<?php

namespace Wintel\RestBundle\Controller;

use Doctrine\DBAL\Connection;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class AgentController
 * @package Wintel\RestBundle\Controller
 */
class AgentController extends Controller
{
    /**
     * @var array
     * 坐席类型
     * -1 =>非坐席，0=>普通坐席,1=>班长坐席
     */
    protected $ag_role = array(-1,0,1);

    /**
     *  静态坐席签入接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function loginAction(Request $request)
    {
        $param = $request->get("param", 0);
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        if (empty($param)) {
            $ret = array(
                'code' => 415,
                'message' => '参数param不能为空',
            );
            return  new JsonResponse($ret);
        }
        $param_row = json_decode($param, true);
        if (!(json_last_error() == JSON_ERROR_NONE)) {
            $ret = array(
                'code' => 403,
                'message' => '参数param不是json格式，无法解析',
            );
            return new JsonResponse($ret);
        }
        $vcc_id = isset($param_row['vcc_id']) ? $param_row['vcc_id'] : '';
        $vcc_code = isset($param_row['vcc_code']) ? $param_row['vcc_code'] : '';
        $data_array = isset($param_row['data']) ? $param_row['data'] : '';
        if (empty($vcc_id) && empty($vcc_code)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID和企业代码都为空',
            );
            return new JsonResponse($ret);
        }
        if (empty($vcc_id) && !empty($vcc_code)) {
            //根据vcc_code 查出vcc_id;
            $vcc_id = $conn->fetchColumn(
                " SELECT vcc_id FROM win_agent WHERE vcc_code = :vcc_code AND is_del=0 Limit 1 ",
                array('vcc_code'=>$vcc_code)
            );
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        if (empty($data_array)) {
            $ret = array(
                'code' => 404,
                'message' => '参数中详细数据data为空',
            );
            return new JsonResponse($ret);
        }
        if (!is_array($data_array)) {
            $ret = array(
                'code' => 405,
                'message' => '参数中详细数据data格式不对，要求为数组',
            );
            return new JsonResponse($ret);
        }
        //判断数组中的每个数据是否格式都正确；
        $success_judge = array(); //存放正确结果判断的数组
        $error_judge = array(); //存放失败结果判断的数组
        $address =$this->container->getParameter('win_ip');
        $port = $this->container->getParameter('win_socket_port');
        $logger = $this->get('logger');
        foreach ($data_array as $value) {
            if (!is_array($value)) {
                $error_judge[] = array(
                    'code' => 405,
                    'message' => '参数中详细数据data格式不对，要求为数组',
                    'data' => $value,
                );
                continue;
            }
            if (!array_key_exists('ag_num', $value) || !array_key_exists('phone', $value)) {
                $error_judge[] = array(
                    'code' => 406,
                    'message' => '参数中详细数据data数组格式不对，必须包含工号ag_num和分机号phone',
                    'data' => $value,
                );
                continue;
            }
            $info = $conn->fetchAll(
                "SELECT a.vcc_id,a.id ag_id,a.ag_num,a.ag_name,getagqu(a.id) agqu,b.id phone_id,
                  b.pho_num pho_num, b.pho_type,b.pho_chan , a.ag_owncaller, a.tellevel
                  FROM win_agent a
                  left join win_phone b on a.vcc_id=b.vcc_id and b.pho_num = :pho_num
                  WHERE a.is_del=0 and a.ag_num = :ag_num AND a.vcc_id = :vcc_id ",
                array('pho_num' => $value['phone'], 'ag_num' => $value['ag_num'], 'vcc_id'=>$vcc_id)
            );

            if (empty($info)) {
                $error_judge[] = array(
                    'code' => 409,
                    'message' => '分机号不存在',
                    'data' => $value,
                );
                continue;
            }
            /* 处理坐席名中的特殊字符 */
            $info[0]['ag_name'] = str_replace('(', '（', $info[0]['ag_name']);
            $info[0]['ag_name'] = str_replace(')', '）', $info[0]['ag_name']);
            $info[0]['ag_name'] = str_replace('|', '', $info[0]['ag_name']);

            if (function_exists('mb_convert_encoding')) {
                $ag_name = mb_convert_encoding($info[0]['ag_name'], "GBK", "UTF-8");
            } else {
                $ag_name = iconv("UTF-8", "GBK", $info[0]['ag_name']);
            }
            $str = "aglogin(".$info[0]['ag_id']."|".$info[0]['vcc_id']."|".$info[0]['phone_id'].
                "|".$info[0]['ag_num']."|".$ag_name."|".$info[0]['pho_num']."|".$info[0]['pho_type'].
                "|".$info[0]['agqu']."|".$info[0]['pho_chan']."|".$info[0]['ag_owncaller'].
                "|".$info[0]['tellevel'].")";

            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            if ($socket === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->debug('无法创建socket：【'.$errorCode.'】'.$errorMsg);
                $error_judge[] = array(
                    'code' => 416,
                    'message' => '签入失败',
                    'data' => $value,
                );
                continue;
            }
            $res = socket_connect($socket, $address, $port);
            //连接失败
            if ($res === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->debug('socket无法连接到【'.$address.':'.$port.'】：【'.$errorCode.'】'.$errorMsg);
                $error_judge[] = array(
                    'code' => 416,
                    'message' => '签入失败',
                    'data' => $value,
                );
                continue;
            }
            $str .= "\r\n\r\n";
            $res = socket_write($socket, $str, strlen($str));
            //发送数据失败
            if ($res === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->debug('socket发送数据失败：【'.$errorCode.'】'.$errorMsg);
                $error_judge[] = array(
                    'code' => 416,
                    'message' => '签入失败',
                    'data' => $value,
                );
                continue;
            }
            $responce = socket_read($socket, 100);
            if (strstr($responce, 'Success')) {
                //记录 成功一个
                $success_judge[] = array(
                    'code' => 200,
                    'message' => 'ok',
                    'data' => $value,
                );
                // make_json_result(1);
            } elseif ($responce === false) {
                //如果出现无法连接服务器
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->debug('socket读取数据失败：【'.$errorCode.'】'.$errorMsg);
                $error_judge[] = array(
                    'code' => 416,
                    'message' => '签入失败',
                    'data' => $value,
                );
            } else {
                // $errname = $responce;
                $responce = explode("\r\n", $responce);
                if (isset($responce[1])) {
                    $errcode = explode(":", $responce[1]);
                    if (isset($errcode[1])) {
                        switch (trim($errcode[1])) {
                            case '1':
                                $error_judge[] = array(
                                    'code' => 407,
                                    'message' => '坐席已初始化',
                                    'data' => $value,
                                );
                                break;
                            case '2':
                                $error_judge[] = array(
                                    'code' => 408,
                                    'message' => '本Socket已初始化',
                                    'data' => $value,
                                );
                                break;
                            case '3':
                                $error_judge[] = array(
                                    'code' => 409,
                                    'message' => '分机号不存在',
                                    'data' => $value,
                                );
                                break;
                            case '4':
                                $error_judge[] = array(
                                    'code' => 410,
                                    'message' => '分机已有坐席使用',
                                    'data' =>  $value,
                                );
                                break;
                            case '5':
                                $error_judge[] = array(
                                    'code' => 411,
                                    'message' => '有队列不存在',
                                    'data' => $value,
                                );
                                break;
                            case '6':
                                $error_judge[] = array(
                                    'code' => 412,
                                    'message' => '已达登录上限',
                                    'data' => $value,
                                );
                                break;
                            case '7':
                                $error_judge[] = array(
                                    'code' => 413,
                                    'message' => '分机类型错误',
                                    'data' => $value,
                                );
                                break;
                            default:
                                $error_judge[] = array(
                                    'code' => 414,
                                    'message' => '格式错误',
                                    'data' => $value,
                                );
                                break;
                        }
                    }
                }
            }
        }
        //抛出最后的结果；
        if (empty($error_judge)) {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );
            return new JsonResponse($ret);
        } else {
            $ret = array(
                'code' => 500,
                'message' => '总错误',
                'errors' => array_merge($error_judge, $success_judge),
            );
            return new JsonResponse($ret);
        }
    }

    /**
     *  静态坐席签出接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function logoutAction(Request $request)
    {
        $param = $request->get("param", 0);
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        if (empty($param)) {
            $ret = array(
                'code' => 415,
                'message' => '参数param不能为空',
            );
            return  new JsonResponse($ret);
        }
        $param_arr = json_decode($param, true);
        if (!(json_last_error() == JSON_ERROR_NONE)) {
            $ret = array(
                'code' => 403,
                'message' => '参数param不是json格式，无法解析',
            );
            return new JsonResponse($ret);
        }
        $vcc_id = isset($param_arr['vcc_id']) ? $param_arr['vcc_id'] : 0;
        $vcc_code = isset($param_arr['vcc_code']) ? $param_arr['vcc_code'] : '';
        if (empty($vcc_id) && empty($vcc_code)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID和企业代码都为空',
            );
            return new JsonResponse($ret);
        }
        if (empty($vcc_id) && !empty($vcc_code)) {
            //根据vcc_code 查出vcc_id;
            $vcc_id = $conn->fetchColumn(
                " SELECT vcc_id FROM win_agent WHERE vcc_code = :vcc_code AND is_del=0 Limit 1 ",
                array('vcc_code'=>$vcc_code)
            );
        }
        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符'
            );
            return new JsonResponse($ret);
        }
        $data = isset($param_arr['data']) ? $param_arr['data'] : array();
        if (empty($data)) {
            $ret = array(
                'code' => 404,
                'message' => '参数中详细数据data为空'
            );
            return new JsonResponse($ret);
        }
        if (!is_array($data)) {
            $ret = array(
                'code' => 405,
                'message' => '参数中详细数据data格式不对，要求为数组'
            );
            return new JsonResponse($ret);
        }
        $success_judge = array(); //存放正确结果判断的数组
        $error_judge = array(); //存放失败结果判断的数组
        $address =$this->container->getParameter('win_ip');
        $port = $this->container->getParameter('win_socket_port');
        $logger = $this->get('logger');
        foreach ($data as $value) {
            if (!is_array($value)) {
                $error_judge[] = array(
                    'code' => 405,
                    'message' => '参数中详细数据data格式不对，要求为数组',
                    'data' => $value,
                );
                continue;
            }
            if (!array_key_exists('ag_num', $value)) {
                $error_judge[] = array(
                    'code' => 406,
                    'message' => '参数中详细数据data数组格式不对，必须包含工号ag_num',
                    'data' => $value,
                );
                continue;
            }
            //得出ag_id;
            $ag_id = $conn->fetchColumn(
                "SELECT id FROM win_agent WHERE ag_num = :ag_num AND vcc_id = :vcc_id AND is_del=0 limit 1",
                array('ag_num'=>$value['ag_num'],'vcc_id'=>$vcc_id)
            );
            $str = "aglogout(".$ag_id.")";
            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            if ($socket === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->debug('无法创建socket：【'.$errorCode.'】'.$errorMsg);
                $error_judge[] = array(
                    'code' => 411,
                    'message' => '签出失败',
                    'data' => $value,
                );
                continue;
            }
            $res = socket_connect($socket, $address, $port);
            //连接失败
            if ($res === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->debug('socket无法连接到【'.$address.':'.$port.'】：【'.$errorCode.'】'.$errorMsg);
                $error_judge[] = array(
                    'code' => 411,
                    'message' => '签出失败',
                    'data' => $value,
                );
                continue;
            }
            $str .= "\r\n\r\n";
            $res = socket_write($socket, $str, strlen($str));
            //发送数据失败
            if ($res === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->debug('socket发送数据失败：【'.$errorCode.'】'.$errorMsg);
                $error_judge[] = array(
                    'code' => 411,
                    'message' => '签出失败',
                    'data' => $value,
                );
                continue;
            }
            $responce = socket_read($socket, 100);
            if ($responce === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->debug('socket读取数据失败：【'.$errorCode.'】'.$errorMsg);
                $error_judge[] = array(
                    'code' => 411,
                    'message' => '签出失败',
                    'data' => $value,
                );
                continue;
            }
            if (strstr($responce, 'Success')) {
                $success_judge[] = array(
                    'code' => 200,
                    'message' => 'ok',
                    'data' => $value,
                );
            } else {
                $responce = explode("\r\n", $responce);
                if (isset($responce[1])) {
                    $errcode = explode(":", $responce[1]);
                    switch (trim($errcode[1])) {
                        case '1':
                            $error_judge[] = array(
                                'code' => 407,
                                'message' => '坐席不存在或坐席没有签入',
                                'data' => $value,
                            );
                            break;
                        case '2':
                            $error_judge[] = array(
                                'code' => 408,
                                'message' => '不是静态坐席',
                                'data' => $value,
                            );
                            break;
                        case '3':
                            $error_judge[] = array(
                                'code' => 409,
                                'message' => '坐席已从页面登录',
                                'data' => $value,
                            );
                            break;
                        default:
                            $error_judge[] = array(
                                'code' => 410,
                                'message' => '格式错误',
                                'data' => $value,
                            );
                            break;
                    }
                }
            }
        }
        //抛出最后的结果；
        if (empty($error_judge)) {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );
            return new JsonResponse($ret);
        } else {
            $ret = array(
                'code' => 500,
                'message' => '总错误',
                'errors' => array_merge($error_judge, $success_judge),
            );
            return new JsonResponse($ret);
        }
    }

    /**
     *  删除坐席接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function deleteAction(Request $request)
    {
        $vcc_id = $request->get("vcc_id", 0);
        $ag_id = $request->get('ag_id', 0);
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }

        if (empty($ag_id)) {
            return new JsonResponse(array('code'=>403, 'message'=>'坐席ID为空'));
        }
        //有批量删除情况
        $ag_arr = json_decode($ag_id);
        $ag_arr = json_last_error() || !is_array($ag_arr) ? array((int)$ag_id) : $ag_arr;
        if (empty($ag_arr)) {
            return new JsonResponse(array('code'=>403, 'message'=>'坐席ID为空'));
        }

        $errorMsg = array();
        foreach ($ag_arr as $ag_id) {
            if (!is_numeric($ag_id)) {
                $errorMsg[] = array(
                    'code' => 404,
                    'message' => '坐席ID包含非数字字符',
                    'ag_id' => $ag_id,
                );
                continue;
            }
            //坐席登陆的不能删除
            $res = $conn->fetchAssoc(
                'SELECT ag_type,ag_sta '.
                'FROM win_agent '.
                'WHERE vcc_id = :vcc_id AND id = :ag_id',
                array('vcc_id'=>$vcc_id, 'ag_id'=>$ag_id)
            );
            if ($res['ag_type']!=1 || $res['ag_sta'] !=0) {
                $errorMsg[] = array(
                    'code' => 406,
                    'message' => '坐席在登录状态',
                    'ag_id' => $ag_id,
                );
                continue;
            }
            $conn->beginTransaction();
            try {
                $conn->update('win_agent', array('is_del'=>1), array('vcc_id'=>$vcc_id,'id'=>$ag_id));
                //删除掉 win_agqu;
                $conn->delete('win_agqu', array('ag_id' => $ag_id));
                $conn->commit();
                $errorMsg[] = array(
                    'code' => 200,
                    'message' => 'ok',
                    'ag_id' => $ag_id,
                );
            } catch (\Exception $e) {
                $conn->rollBack();
                $errorMsg[] = array(
                    'code' => 405,
                    'message' => '删除失败',
                    'ag_id' => $ag_id,
                );
            }
        }
        return new JsonResponse(array('code'=>500, 'message'=>'总结果', 'data'=>$errorMsg));
    }
    /**
     *  编辑坐席接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function editAction(Request $request)
    {
        $vcc_id = $request->get("vcc_id", 0);
        $ag_id = $request->get('ag_id', 0);
        $ag_name = $request->get('ag_name', 0);
        $ag_password = $request->get('ag_password', '');
        $ag_nickname = $request->get('ag_nickname', '');
        $ag_role = $request->get('ag_role', false); //坐席前台类型
        $user_role = $request->get('user_role', false); //坐席角色
        $ag_status = $request->get('ag_status', ''); //坐席状态 1在职 2离职 3冻结
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }

        if (empty($ag_id)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($ag_id)) {
            $ret = array(
                'code' => 404,
                'message' => '坐席ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        if (empty($ag_name)) {
            $ret = array(
                'code' => 405,
                'message' => '坐席名称为空',
            );
            return new JsonResponse($ret);
        }

        //前台坐席类型 406
        if (!in_array($ag_role, $this->ag_role)) {
            $ret = array(
                'code' => 406,
                'message' => '坐席类型不正确',
            );
            return new JsonResponse($ret);
        }

        //407 坐席角色是否属于该企业
        if (!empty($user_role)) {
            $msg = $this->get('validator.custom')->vccRole($vcc_id, $user_role, 407);
            if (!empty($msg) && is_array($msg)) {
                return new JsonResponse($msg);
            }
        }

        $data = array(
            'ag_name' => $ag_name,
        );
        if($ag_nickname !== '') {
            $data['ag_nickname'] = $ag_nickname;
        }
        if ($user_role !== false) {
            $data['user_role'] = $user_role;
        }
        if ($ag_role !== false) {
            $data['ag_role'] = $ag_role;
        }
        if ($ag_status !== '') {
            if (in_array($ag_status, array(1,2,3))) {
                $data['ag_status'] = $ag_status;
            } else {
                $ret = array(
                    'code' => 407,
                    'message' => '未知坐席状态',
                );
                return new JsonResponse($ret);
            }
        }
        if (!empty($ag_password)) {
            $data = array_merge($data, array('ag_password'=>$ag_password));
        }
        $conn = $this->get('doctrine.dbal.default_connection');
        try {
            /** @var \Doctrine\DBAL\Connection $conn */
            $conn->update('win_agent', $data, array('vcc_id'=>$vcc_id,'id'=>$ag_id));
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );
            $data['ag_id'] = $ag_id;
            $data['vcc_id'] = $vcc_id;
            $this->get('icsoc_data.model.agent')->writeMq(array('action' => 'update', 'data' => $data));

            return new JsonResponse($ret);
        } catch (\Exception $e) {
            $ret = array(
                'code' => 408,
                'message' => '编辑失败',
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * 批量修改坐席状态
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function editAllAction(Request $request)
    {
        $vccId = $request->get('vcc_id', '');
        $agIds = $request->get('ag_ids', '');
        $agStatus = $request->get('ag_status', '');

        if (empty($vccId)) {
            return new JsonResponse(array('code' => 400, 'message' => '企业ID不存在'));
        }
        if (empty($agIds)) {
            return new JsonResponse(array('code' => 401, 'message' => '坐席ID不存在'));
        }
        if (empty($agStatus) || !in_array($agStatus, array(1,2,3))) {
            return new JsonResponse(array('code' => 402, 'message' => '坐席状态不正确'));
        }

        try{
            /** @var \Doctrine\DBAL\Connection $conn */
            $conn = $this->get("doctrine.dbal.default_connection");
            $conn->executeQuery(
                "UPDATE win_agent SET ag_status=$agStatus WHERE vcc_id=$vccId AND id IN($agIds)"
            );

            return new JsonResponse(array('code' => 200, 'message' => 'ok'));
        } catch (\Exception $e) {
            $ret = array(
                'code' => 403,
                'message' => '编辑失败',
            );
            return new JsonResponse($ret);
        }
    }

    /**
     *  新建坐席接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function addAction(Request $request)
    {
        $vcc_id = $request->get("vcc_id", 0);
        $que_id = $request->get('que_id', 0);
        $ag_num = $request->get('ag_num', '');
        $ag_name = $request->get('ag_name', '');
        $ag_nickname = $request->get('ag_nickname', '');
        $ag_password = $request->get('ag_password', '');
        $ag_role = $request->get('ag_role', 0); //坐席前台类型
        $user_role = $request->get('user_role', ''); //坐席角色
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        //判断企业ID 是否存在；
        $vcc_code = $conn->fetchColumn(
            "SELECT vcc_code FROM cc_ccods WHERE status=1 AND vcc_id=:vcc_id",
            array('vcc_id'=>$vcc_id)
        );
        if (empty($vcc_code)) {
            $ret = array(
                'code' => 403,
                'message' => '企业ID不存在',
            );
            return new JsonResponse($ret);
        }

        //判断技能组ID
        if (!empty($que_id)) {
            if (!is_numeric($que_id)) {
                $ret = array(
                    'code' => 405,
                    'message' => '技能组ID包含非数字字符',
                );
                return new JsonResponse($ret);
            }
            $que_if_exits = $conn->fetchColumn(
                "SELECT id FROM win_queue WHERE vcc_id=:vcc_id AND id=:que_id AND is_del=0",
                array('vcc_id'=>$vcc_id,'que_id'=>$que_id)
            );
            if (!$que_if_exits) {
                $ret = array(
                    'code' => 406,
                    'message' => '技能组ID不存在',
                );
                return new JsonResponse($ret);
            }
        }
        //在判断ag_num
        if (empty($ag_num)) {
            $ret = array(
                'code' => 407,
                'message' => '坐席工号为空',
            );
            return new JsonResponse($ret);
        }
        /*
        if (!is_numeric($ag_num)) {
            $ret = array(
                'code' => 408,
                'message' => '坐席工号包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        */
        //is_delete=0这个条件不知道应该加不；
        $ag_num_if_exists = $conn->fetchColumn(
            "SELECT id FROM win_agent WHERE vcc_id = :vcc_id AND is_del = 0 AND ag_num = :ag_num",
            array('vcc_id'=>$vcc_id,'ag_num'=>$ag_num)
        );
        if ($ag_num_if_exists) {
            $ret = array(
                'code' => 409,
                'message' => '坐席工号已经存在',
            );
            return new JsonResponse($ret);
        }

        //坐席名称
        if (empty($ag_name)) {
            $ret = array(
                'code' => 410,
                'message' => '坐席名称为空',
            );
            return new JsonResponse($ret);
        }
        //坐席密码
        if (empty($ag_password)) {
            $ret = array(
                'code' => 411,
                'message' => '坐席密码为空',
            );
            return new JsonResponse($ret);
        }

        //前台坐席类型
        if (!in_array($ag_role, $this->ag_role)) {
            $ret = array(
                'code' => 412,
                'message' => '坐席类型不正确',
            );
            return new JsonResponse($ret);
        }

        //坐席角色是否属于该企业
        if (!empty($user_role)) {
            $msg = $this->get('validator.custom')->vccRole($vcc_id, $user_role, 413);
            if (!empty($msg) && is_array($msg)) {
                return new JsonResponse($msg);
            }
        }

        //查看最大坐席数
        $agents = $conn->fetchColumn(
            'SELECT agents '.
            'FROM cc_ccods '.
            'WHERE vcc_id = :vcc_id ',
            array('vcc_id'=>$vcc_id)
        );

        $alreay = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_agent '.
            'WHERE vcc_id = :vcc_id AND ag_role <> -1 AND is_del = 0',
            array('vcc_id'=>$vcc_id)
        );

        if ($alreay >= $agents) {
            $ret = array(
                'code' => 415,
                'message' => '坐席已经数量达到极限',
            );
            return new JsonResponse($ret);
        }

        $conn->beginTransaction();
        try {
            $data = array(
                'vcc_id' => $vcc_id,
                'vcc_code' => $vcc_code,
                'ag_num' => $ag_num,
                'ag_password' => $ag_password,
                'ag_name' => $ag_name,
                'user_role' => $user_role,
                'ag_role' => $ag_role,
                'ag_nickname' => $ag_nickname
            );
            $conn->insert('win_agent', $data);
            $ag_id = $conn->lastInsertId();
            //分配到技能组
            if (!empty($que_id)) {
                $conn->insert('win_agqu', array('que_id'=>$que_id,'ag_id'=>$ag_id,'skill'=>1));
            }
            $conn->commit();
            $ret = array(
                'code' => 200,
                'lastId' => $ag_id,
                'message' => 'ok',
            );
            return new JsonResponse($ret);
        } catch (Exception $e) {
            $conn->rollBack();
            $ret = array(
                'code' => 414,
                'message' => '添加坐席失败['.$e->getMessage().']'
            );
            return new JsonResponse($ret);
        }

    }

    /**
     * 获取企业下的坐席信息接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function listAction(Request $request)
    {
        $vcc_id = $request->get("vcc_id", 0);
        $ag_id = $request->get("ag_id", 0);
        $que_id = $request->get('que_id', 0);
        $info = $request->get('info', ''); //分页搜索相关信息；
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");

        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }

        if (!empty($ag_id)) {
            if (!is_numeric($ag_id)) {
                $ret = array(
                    'code' => 403,
                    'message' => '坐席ID包含非数字字符',
                );
                return new JsonResponse($ret);
            }
        }

        $addInfo = array(); //分页搜索相关信息；
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 404, 'message'=>'info格式非json'));
            }
        }

        $where = '';
        if (isset($addInfo['filter'])) {
            $where = isset($addInfo['filter']['account']) && !empty($addInfo['filter']['account']) ?
                " AND ag_num LIKE '%".$addInfo['filter']['account']."%' " : '';
            $where.= isset($addInfo['filter']['pho_num']) && !empty($addInfo['filter']['pho_num']) ?
                " AND pho_num LIKE '%".$addInfo['filter']['pho_num']."%' AND ag_type = 2 " : '';
        }
        $where.= !empty($ag_id) ? " AND a.id = :ag_id " : '';
        $where.= !empty($que_id) ? ' AND ag.que_id = :que_id ' : '';
        $params = !empty($ag_id) ? array('vcc_id'=>$vcc_id, 'ag_id'=>$ag_id) : array('vcc_id'=>$vcc_id);
        $params = !empty($que_id) ? array_merge($params, array('que_id'=>$que_id)) : $params;
        $joinTable = $skill = '';
        if (!empty($que_id)) {
            $joinTable = ' LEFT JOIN win_agqu as ag ON ag.ag_id = a.id ';
            $skill = ',ag.skill ';
        }
        //查出总计的条数
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_agent as a '.$joinTable.
            'WHERE a.vcc_id = :vcc_id AND a.is_del = 0 '.$where,
            $params
        );

        $limit = isset($addInfo['pagination']['rows']) ?  $addInfo['pagination']['rows'] : 1000;
        $total_pages = ceil($count/$limit);
        $page = isset($addInfo['pagination']['page']) ? $addInfo['pagination']['page'] : 1;
        $page = $page > $total_pages ? $total_pages : $page;
        $start = $limit*$page - $limit;
        $start = $start > 0 ? $start : 0;
        $flag = false;
        if (isset($addInfo['sort']['field'])) {
            //就需要验证传入字段是否属于坐席表
            $flag = $this->get('validator.extend.custom')->fieldExistTable($addInfo['sort']['field'], 'win_agent');
        }
        $sort = $flag ? $addInfo['sort']['field'] : 'id';
        $order = isset($addInfo['sort']['order']) && in_array(strtolower($addInfo['sort']['order']), array('desc','asc'))
            ? $addInfo['sort']['order'] : 'desc';
        //开始查询
        $sql = "SELECT a.id as ag_id,a.vcc_id,a.ag_num,a.ag_name,a.ag_password,a.ag_role,".
            "a.user_role,r.name as role_name,a.ag_type,a.pho_num ".$skill.
            'FROM win_agent as a '.
            'LEFT JOIN cc_roles as r '.
            'ON a.user_role = r.role_id '.$joinTable.
            " WHERE a.vcc_id = :vcc_id AND a.is_del = 0 ";
        $sql.=$where."  ORDER BY a.$sort $order LIMIT $start,$limit";
        $data = $conn->fetchAll($sql, $params);
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $data,
        );
        return new JsonResponse($ret);
    }

    /**
     * 修改坐席密码
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function updatepassAction(Request $request)
    {
        $vcc_id = $request->get("vcc_id", 0);
        $ag_id = $request->get("ag_id", 0);
        $old_password = $request->get("old_password", '');
        $new_password = $request->get("new_password", '');
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        if (empty($ag_id)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ID为空',
            );
            return new JsonResponse($ret);
        }
        if (!is_numeric($ag_id)) {
            $ret = array(
                'code' => 404,
                'message' => '坐席ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }

        if (empty($old_password)) {
            $ret = array(
                'code' => 405,
                'message' => '旧密码为空',
            );
            return new JsonResponse($ret);
        }

        //验证旧密码是否正确
        $password = $conn->fetchColumn(
            "SELECT ag_password FROM win_agent WHERE id=:ag_id AND vcc_id=:vcc_id ",
            array('vcc_id'=>$vcc_id,'ag_id'=>$ag_id)
        );
        if ($password != $old_password) {
            $ret = array(
                'code' => 406,
                'message' => '旧密码错误',
            );
            return new JsonResponse($ret);
        }
        //新密码为空
        if (empty($new_password)) {
            $ret = array(
                'code' => 407,
                'message' => '新密码为空',
            );
            return new JsonResponse($ret);
        }
        try {
            $conn->update(
                "win_agent",
                array('ag_password'=>$new_password),
                array('vcc_id'=>$vcc_id, 'id'=>$ag_id)
            );
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );
            return new JsonResponse($ret);
        } catch (Exception $e) {
            $ret = array(
                'code' => 408,
                'message' => '修改失败['.$e->getMessage().']',
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * 坐席登录接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */

    public function signinAction(Request $request)
    {
        $vcc_code = $request->get('vcc_code');
        $ag_num = $request->get('ag_num');
        $password = $request->get('password');
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        //vcc_code 验证
        $msg = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }
        if (empty($ag_num)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席工号为空',
            );
            return new JsonResponse($ret);
        }
        if (empty($password)) {
            $ret = array(
                'code' => 404,
                'message' => '密码为空',
            );
            return new JsonResponse($ret);
        }
        $agentData = $conn->fetchAssoc(
            "SELECT id,vcc_id,ag_num,ag_name,ag_password,ag_status FROM win_agent WHERE vcc_code=:vcc_code
            AND ag_num=:ag_num AND is_del=0",
            array('vcc_code' => $vcc_code, 'ag_num' => $ag_num)
        );
        if (empty($agentData)) {
            $ret = array(
                'code' => 405,
                'message' => '工号不存在',
            );

            return new JsonResponse($ret);
        }
        if ($agentData['ag_status'] == 3) {
            $ret = array(
                'code' => 406,
                'message' => '您的账号被锁定，请联系管理员解除锁定',
            );

            return new JsonResponse($ret);
        }
        if ($agentData['ag_status'] == 2) {
            $ret = array(
                'code' => 407,
                'message' => '对不起，您已离职',
            );

            return new JsonResponse($ret);
        }
        if ($agentData['ag_password'] != $password) {
            $ret = array(
                'code' => 408,
                'message' => '坐席工号或密码错误',
                'ag_id' => $agentData['id'],
                'vcc_id' => $agentData['vcc_id'],
                'ag_name' => $agentData['ag_name'],
            );

            return new JsonResponse($ret);
        }

        $result = $conn->fetchAssoc(
            "SELECT wa.id AS ag_id,cc.vcc_id,cc.db_main_ip,cc.db_slave_ip,cc.db_name,
            cc.db_user,cc.db_password,cc.role_action,cc.is_enable_newworkflow,wa.group_id,wg.group_name,
            cc.system_version,ccs.tel_addr,ccs.tel_port,ccs.addr_flash,ccs.addr_websocket,ccf.is_enable_black,ccf.is_incoming_enable_black,ccf.is_enable_white,cc.sms_vendor_id
            FROM win_agent as wa
            LEFT JOIN cc_ccods AS cc
            ON cc.vcc_id = wa.vcc_id
            LEFT JOIN cc_ccod_configs ccf
            ON ccf.vcc_id = wa.vcc_id
            LEFT JOIN win_group AS wg
            ON wa.group_id = wg.group_id
            LEFT JOIN cc_cti_servers AS ccs
            ON cc.telid=ccs.telid
            WHERE wa.vcc_code=:vcc_code AND wa.ag_num=:ag_num
            AND wa.ag_password=:password AND wa.is_del=0",
            array('vcc_code'=>$vcc_code, 'ag_num'=>$ag_num,'password'=>$password)
        );
        if (empty($result)) {
            $ret = array(
                'code' => 409,
                'message' => '验证失败,没有匹配到相应数据',
            );
            return new JsonResponse($ret);
        } else {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
                'data' => $result,
            );
            return new JsonResponse($ret);
        }
    }

    /**
     *  获取当前空闲坐席接口
     * @param integer
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function freeAction($vcc_id)
    {
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        $list = $conn->fetchAll(
            "SELECT ag_id,pho_num,ag_name,ag_num FROM win_agmonitor WHERE ag_sta=1 AND vcc_id=:vcc_id LIMIT 20",
            array('vcc_id'=>$vcc_id)
        );

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $list,
        );
        return new JsonResponse($ret);
    }

    /**
     *  获取当前通话中的坐席
     * @param integer
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function onthelineAction($vcc_id)
    {
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        $list = $conn->fetchAll(
            "SELECT ag_id,pho_num,sec_to_time(unix_timestamp()-pho_sta_time)as ag_time FROM win_agmonitor ".
            " WHERE pho_sta=2 AND vcc_id=:vcc_id LIMIT 20",
            array('vcc_id'=>$vcc_id)
        );

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $list,
        );
        return new JsonResponse($ret);
    }

    /**
     *  设置坐席转接电话接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *
     */
    public function agextphoneAction(Request $request)
    {
        $vcc_id = $request->get('vcc_id');
        $ag_id = $request->get('ag_id');
        $phone = $request->get('phone');
        $state = $request->get('state', 1);
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }

        if (empty($ag_id)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ID为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($ag_id)) {
            $ret = array(
                'code' => 404,
                'message' => '坐席ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }

        if (empty($phone)) {
            $ret = array(
                'code' => 405,
                'message' => '手机号为空',
            );
            return new JsonResponse($ret);
        }

        if (!is_numeric($phone)) {
            $ret = array(
                'code' => 406,
                'message' => '手机号码含非数字字符',
            );
            return new JsonResponse($ret);
        }

        if (strlen($phone)!=11) {
            $ret = array(
                'code' => 407,
                'message' => '手机号码不是11位',
            );
            return new JsonResponse($ret);
        }

        if (!in_array($state, array(1,0))) {
            $ret = array(
                'code' => 408,
                'message' => '状态值不是0或1',
            );
            return new JsonResponse($ret);
        }

        //判断ag_id 是否存在
        $agent = $conn->fetchAssoc(
            "SELECT id FROM win_agent WHERE is_del=0 AND vcc_id=:vcc_id AND id=:ag_id",
            array('vcc_id' => $vcc_id,'ag_id' => $ag_id)
        );

        if (empty($agent)) {
            $ret = array(
                'code' => 409,
                'message' => '对应的坐席不存在',
            );
            return new JsonResponse($ret);
        }

        $res = $conn->exec(
            "INSERT INTO win_agextphone(vcc_id,ag_id,pho_num,state)".
            "VALUES('$vcc_id','$ag_id','$phone','$state') ".
            "ON DUPLICATE KEY UPDATE pho_num='$phone',state='$state'"
        );
        if ($res) {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );
            return new JsonResponse($ret);
        } else {
            $ret = array(
                'code' => 410,
                'message' => '设置失败',
            );
            return new JsonResponse($ret);
        }
    }
}
